package com.example.scan;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class ScanBroadcastReceiver extends BroadcastReceiver {
    public static final String ACTION_SCAN_RESULT = "com.action.SCAN_RESULT";
    public static final String ACTION_SCAN_STATE = "com.action.SCAN_STATE";
    private ScanManager scanManager;
    private ScanResultListener listener;

    public ScanBroadcastReceiver(ScanManager scanManager, ScanResultListener listener) {
        this.scanManager = scanManager;
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_SCAN_RESULT.equals(action)) {
            byte[] barcodeArray = intent.getByteArrayExtra("scanContext");
            String barcode = new String(barcodeArray, 0, barcodeArray.length);
            listener.onScanResult(barcode);
        } else if (ACTION_SCAN_STATE.equals(action)) {
            int state = intent.getIntExtra("state", 0);
            handleScanState(state);
            listener.onScanState(state);
        }
    }

    private void handleScanState(int state) {
        switch (state) {
            case 0: // close
            case 2: // decode timeout
                scanManager.stopDecode();
                break;
            case 1: // open
                if (scanManager.isContinuousDecode()) {
                    scanManager.startContinuousDecode();
                }
                break;
            case -1: // error
                scanManager.stopDecode();
                scanManager.stopContinuousDecode();
                break;
        }
    }
}